package com.juzhi.dvrapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.bean.DeviceUser;
import com.juzhi.dvrapp.bean.LzyResponse;
import com.juzhi.dvrapp.bean.MessageEven2Refresh;
import com.juzhi.dvrapp.callback.DialogCallback;
import com.juzhi.dvrapp.manager.AppManager;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.service.BridgeService;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.MLog;
import com.juzhi.dvrapp.utils.T;
import com.juzhi.dvrapp.utils.Urls;
import com.juzhi.dvrapp.widget.DividerItemDecoration;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mcxtzhang.commonadapter.rv.CommonAdapter;
import com.mcxtzhang.commonadapter.rv.HeaderFooterAdapter;
import com.mcxtzhang.commonadapter.rv.IHeaderHelper;
import com.mcxtzhang.commonadapter.rv.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseAcitivity {


    @BindView(R.id.main_rv)
    RecyclerView mRecyclerView;
    @BindView(R.id.activity_main_swipe_refresh)
    SwipeRefreshLayout mSwipeRefresh;
    private CommonAdapter<Device> mAdapter;
    private List<Device> mDatas = new ArrayList<>();
    private DeviceManager deviceManager;
    private AlertDialog alertDialog;
    private HeaderFooterAdapter mHeaderFooterAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        MLog.w("initView---------");

        initHeaderView();
        setTitleText(getResources().getString(R.string.app_name));

        deviceManager = DeviceManager.getDeviceManager(this);
        mDatas = deviceManager.getRemoteDevice();

        registEventBus();


        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mAdapter = new CommonAdapter<Device>(this, mDatas, R.layout.activity_device_item) {

            @Override
            public void convert(final ViewHolder viewHolder, final Device device) {

                getDeviceStatus(device, viewHolder);
                viewHolder.setOnClickListener(R.id.main_rv_device_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityInfo(device);
//                        goToPlayEmptyControlActivity(MainActivity.this,v);
                    }
                });
                viewHolder.setOnClickListener(R.id.activity_main_remote_device_del, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deviceManager.deleteDevice(device);
                        mDatas.clear();
                        mDatas = deviceManager.getRemoteDevice();
                        mHeaderFooterAdapter.notifyDataSetChanged();
                    }
                });
                viewHolder.setOnClickListener(R.id.rv_device_play_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (device.getStatus() == Config.DEVICE_RESULT_SUCCESS){
                            Intent intent = new Intent(MainActivity.this,DevicePlayAndMapActivity.class);
                            intent.putExtra(Config.SSID, device.getDeviceModel().getSsid());
                            startActivity(intent);
                        }else {
                            T.showShort(getString(R.string.string_device_type_error));
                        }

                    }
                });

                viewHolder.setOnClickListener(R.id.rv_device_message_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (device.getStatus() == Config.DEVICE_RESULT_SUCCESS){
                            Intent intent = new Intent(MainActivity.this,DeviceMessageActivity.class);
                            intent.putExtra(Config.SSID, device.getDeviceModel().getSsid());
                            startActivity(intent);
                        }else {
                            T.showShort(getString(R.string.string_device_type_error));
                        }
                    }
                });
            }
        };

        mHeaderFooterAdapter = new HeaderFooterAdapter(mAdapter);
        mHeaderFooterAdapter.setHeaderView(0, new IHeaderHelper() {
            @Override
            public int getItemLayoutId() {
                return R.layout.activity_main_recycler_head;
            }

            @Override
            public void onBind(ViewHolder viewHolder) {
                Device localDevice = deviceManager.getLocalDevice();
                MLog.w("头布局刷新----- mData-----"+mDatas.size());

                if (localDevice == null) {
                    viewHolder.setVisible(R.id.activity_main_local_device,false);
                    viewHolder.setVisible(R.id.activity_main_local_device_default,true);
                } else {
                    viewHolder.setVisible(R.id.activity_main_local_device,true);
                    viewHolder.setVisible(R.id.activity_main_local_device_default,false);
                }

                if (mDatas.size() == 0)
                    viewHolder.setVisible(R.id.activity_main_remote_device,true);
                else {
                    viewHolder.setVisible(R.id.activity_main_remote_device, false);
                }
            }
        });

        mRecyclerView.setAdapter(mHeaderFooterAdapter);

        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                MLog.w("下拉刷新---------");

                deviceManager.connectionDevice();
                mHeaderFooterAdapter.notifyDataSetChanged();
                mSwipeRefresh.setRefreshing(false);
            }
        });

    }

    private void startActivityInfo(Device device) {
        if (device.getStatus() == Config.DEVICE_RESULT_SUCCESS) {
            Intent intent = new Intent(MainActivity.this, DeviceInfoActivity.class);
            intent.putExtra(Config.SSID, device.getDeviceModel().getSsid());
            startActivity(intent);
        } else if (device.getStatus() == Config.DEVICE_RESULT_ERROR_SSID || device.getStatus() == Config.DEVICE_RESULT_ERROR_PWD) {
            Intent intent = new Intent(MainActivity.this, DeviceEditActivity.class);
            intent.putExtra(Config.SSID, device.getDeviceModel().getSsid());
            startActivity(intent);
        } else if (device.getStatus() == Config.DEVICE_RESULT_ERROR_LOGIN) {
            showConstraintLogin(device);
        } else if (device.getStatus() == Config.DEVICE_RESULT_OFFLINE) {
            T.showShort(getResources().getString(R.string.main_device_prompt));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(MessageEven2Refresh even2Refresh) {
        mDatas.clear();
        mDatas.addAll(deviceManager.getRemoteDevice());
        mHeaderFooterAdapter.notifyDataSetChanged();
        MLog.w("onMessage -----------  刷新");
    }

    @OnClick(R.id.main_add_device_btn)
    public void onViewClicked() {
        Intent intent = new Intent(this, DeviceAddActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        MLog.w("onNewIntent----------");
        mDatas.clear();
        mDatas.addAll(deviceManager.getRemoteDevice());
        mAdapter.setDatas(mDatas);
        mHeaderFooterAdapter.notifyDataSetChanged();
    }

    @Override
    protected void back() {
        _exit();
    }

    /**
     * 退出按钮
     */
    @Override
    public void onBackPressed() {
        _exit();
    }

    long mExitTime = 0;

    /**
     * 退出
     */
    private void _exit() {

        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this, getString(R.string.string_exit_again), Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().AppExit(this);
        }
    }

    public void getDeviceStatus(Device device, ViewHolder viewHolder) {
        String mStatusStr = null;
        Drawable mDrawable = null;
        switch (device.getStatus()) {
            case 200:
                mStatusStr = getResources().getString(R.string.device_online);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img);
                break;
            case 201:
                mStatusStr = getResources().getString(R.string.string_status_connect_httpservice_error);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_error);
                break;
            case 202:
                mStatusStr = getResources().getString(R.string.string_status_connect_ssid_error);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_error);
                break;
            case 203:
                mStatusStr = getResources().getString(R.string.string_status_connect_login_errer);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_error);
                break;
            case 204:
                mStatusStr = getResources().getString(R.string.string_status_connect_haslogin_errer);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_error);
                break;
            case 205:
                mStatusStr = getResources().getString(R.string.device_not_online);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_off);
                break;
            case -1:
                mStatusStr = getResources().getString(R.string.string_status_connect_timeout_error);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_error);
                break;
            case 1:
                mStatusStr = getResources().getString(R.string.string_status_connecting);
                mDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_device_img_off);
                break;
        }

        viewHolder.setText(R.id.activity_main_remote_device_name, device.getDeviceModel().getDeviceName());
        viewHolder.setText(R.id.activity_main_remote_device_state, mStatusStr);
        viewHolder.setImageDrawable(R.id.activity_main_remote_device_img, mDrawable);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog != null) {
            if (alertDialog.isShowing())
                alertDialog.dismiss();
        }
        unRegistEventBus();

        Intent intent = new Intent(this, BridgeService.class);
        stopService(intent);
    }

    private void showConstraintLogin(final Device device) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_hide));
        dialog.setMessage(getResources().getString(R.string.string_connect_haslogin));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OkGo.<LzyResponse<DeviceUser>>post(Urls.URL_DEVICECONSTRAINTLOGIN)
                        .tag(MainActivity.this)
                        .params(Config.DEVICEID, device.getDeviceModel().getSsid())
                        .params(Config.USERNAME, device.getDeviceModel().getUserName())
                        .execute(new DialogCallback<LzyResponse<DeviceUser>>(MainActivity.this) {
                                    @Override
                                    public void onSuccess(Response<LzyResponse<DeviceUser>> response) {
                                        LzyResponse<DeviceUser> body = response.body();
                                        if(response.body().status == Config.DEVICE_RESULT_SUCCESS){
                                            device.setStatus(body.status);
                                            device.setSystemLevel(body.result.getType());

                                            getDeviceInfo(device);
                                        }else {
                                            T.showShort(getResources().getString(R.string.string_logindevice_error));
                                        }
                                    }

                                    @Override
                                    public void onError(Response<LzyResponse<DeviceUser>> response) {
                                        super.onError(response);
                                        T.showShort(getResources().getString(R.string.string_logindevice_error));
                                    }
                                });

            }
        }).setNegativeButton(getResources().getString(R.string.string_cancel), null);

        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();

        //修改dialog窗体大小
/*        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm); // 获取屏幕宽、高度
        WindowManager.LayoutParams attributes = alertDialog.getWindow().getAttributes();
        attributes.gravity = Gravity.CENTER;
        attributes.width = (int) (dm.widthPixels * 0.7);
        attributes.height = (int) (dm.heightPixels * 0.2);
        alertDialog.getWindow().setAttributes(attributes);*/
    }


/*    public void goToPlayEmptyControlActivity(Activity activity, View view) {
        Intent intent = new Intent(activity, TestPlayActivity.class);
        intent.putExtra(TestPlayActivity.TRANSITION, true);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            Pair pair = new Pair<>(view, TestPlayActivity.IMG_TRANSITION);
            ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                    activity, pair);
            ActivityCompat.startActivity(activity, intent, activityOptions.toBundle());
        } else {
            activity.startActivity(intent);
            activity.overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        }
    }*/
}
